var userCacheData;// 全局用户信息缓存

var chooseUserPlug={
    params:{},
    selectEle:[],
    init:function (ele,options) {
        var params = {
            url:'',
            multiple:false,
            width:'200px',
            placeholder: '请选择',
            allowClear:true,
            requestUrl:sysInfo.basePath+'/zzsc/common/user_choose_page.do',
            select:true,
            otherParam:{
                type:'all'
            },
            yesFun:function () {

            }
        };
        //判断是否 已经初始化
        if(ele.parents('.choose-user-warp').length!=0){
            return false;
        }
        // debugger;
        chooseUserPlug.params=params;
        var chooseSelect;
        //这里会将传入otherParams的对象，覆盖这个js字段的值
        chooseUserPlug.params = $.extend({}, chooseUserPlug.params , options);

        ele.wrap('<div class="choose-user-warp"></div>');
        if(chooseUserPlug.params.select) {
            $.ajax({
                async:false,
                type:'get',
                url:chooseUserPlug.params.url,
                dataType:'json',
                data:chooseUserPlug.params.otherParam,
                success:function(result){
                    if(result.data!=undefined&&result.data!=null){
                        userCacheData = $.map(result.data, function (obj) {
                            obj.text = obj.realName+obj.loginName;
                            return obj;
                        });
                    }
                }
            });
            ele.each(function () {
                var i=chooseUserPlug.selectEle.length;
                var selectObj=$(this).select2({
                    width:chooseUserPlug.params.width,
                    placeholder: chooseUserPlug.params.placeholder,
                    allowClear: chooseUserPlug.params.allowClear,
                    language:"zh-CN",
                    multiple : chooseUserPlug.params.multiple,
                    data:userCacheData,
                    escapeMarkup: function (markup) { return markup; },
                    templateResult: function formatRepo(repo){
                        if (repo.loading) return repo.realName+repo.loginName;
                        var markup = '<div class="clearfix" data-unit='+repo.id+'>'+repo.realName+repo.loginName+'</div>';
                        return markup;
                    },
                    templateSelection: function formatRepoSelection(repo,e){
                        return repo.realName+repo.loginName;
                    },
                    formatSelection: function formatRepoSelection(repo) {
                        return repo.text;
                    }
                });
                chooseUserPlug.selectEle.push(selectObj)
                $(this).parent().append('<a href="javascript:void(0)" class="choose-opt" onclick="chooseUserPlug.chooseUserEvent($(this),'+i+','+chooseUserPlug.params.multiple+')"></a>');
            });
        }else {
            ele.each(function () {
                var i=chooseUserPlug.selectEle.length;
                var inputWin=parseFloat(chooseUserPlug.params.width)-22+'px'
                $(this).before('<span class="select2-selection__clear" onclick="chooseUserPlug.clearUser(this)">×</span><input type="text" class="input-style chooseUser-input" style="width: '+inputWin+'" readonly onclick="chooseUserPlug.chooseUserEvent($(this),'+i+','+chooseUserPlug.params.multiple+','+chooseUserPlug.params.select+')"/>');
            })
        }
    },
    chooseUserEvent:function (obj,i,check,select) {
        /*
        * @param obj 指向当前点击元素
        * @param i 为当前点击元素做标识
        * @param check 判断多选还是单选
        * @param select 判断是否有使用select2
        * */
        // debugger;
        var chooseSelect=chooseUserPlug.selectEle[i];
        dgg.loading();
        $.ajax({
            url:chooseUserPlug.params.requestUrl,
            data:chooseUserPlug.params.otherParam,
            dataType:'html',
            success:function (res) {
                dgg.Open({
                    title:'选择人员',
                    content:res,
                    area:'800px',
                    success:function(layero, index){
                        $('.layerIndex').val(index);
                        var tableUser=chooseUserPlug.tableInit(check);
                        /**
                         * 重新加载表格数据,重置start 和limit参数
                         */
                        $('#searchTable').click(function () {
                            tableUser.ajax.reload();
                        })
                        dgg.loading('close');
                    },
                    yes:function (index) {
                        // debugger;
                        var chooseDate=$('#chooseUserTable').dataTableExtend('getCheck');
                        if(select!=undefined&&!select) {
                            var optionHtm;
                            for(var key in chooseDate   ) {
                                optionHtm+='<option value="'+chooseDate[key].id+'">'+chooseDate[key].realName+'</option>';
                                obj.parent().find('input').val(chooseDate[key].realName)
                            }
                            obj.parent().find('select').empty().append(optionHtm);
                        }else {
                            var echoData=obj.parent().find('select').select2("val");
                            if(check) {
                                (echoData==''||echoData==null) && (echoData=[]);
                                (typeof (echoData)!='object') && (echoData=echoData.split(','));
                                for(var key in chooseDate   ) {
                                    echoData.push(chooseDate[key].id);
                                }
                            }else {
                                echoData=chooseDate[0].id;
                            }
                            // debugger;
                            chooseSelect.val(echoData).trigger("change");
                            chooseSelect.change();
                        }
                        layer.close(index);
                        chooseUserPlug.params.yesFun();
                    }
                })
            }
        })
    },
    tableInit:function (checked) {
        // 加载查询条件部门数据
        var oneSelectCheck=true,selectCheck=false;
        if(checked) {
            oneSelectCheck=false;
            selectCheck=true;
        }else {
            oneSelectCheck=true;
            selectCheck=false;
        }
        var tableUser = $('#chooseUserTable').dataTableExtend({
            "ajax": sysInfo.basePath+"/zzsc/common/user_choose_data.do",
            "fnServerParams": function (aoData) {
                // debugger;
                //如果搜索用户条件为空，就搜索全部
                if(isEmpty(chooseUserPlug.params.otherParam)){
                    chooseUserPlug.params.otherParam.type='all';
                }

                // var type=chooseUserPlug.params.otherParam.type;
                // (type==''||type==undefined)&&(chooseUserPlug.params.otherParam.type='all');

                //将页面跳转传递参数，设置到搜索条件中
                aoData = $.extend(aoData,chooseUserPlug.params.otherParam);

                //因待分配页面会传递部门id，在获取搜索框搜索条件的时候，初始化为空，会被覆盖，所有手动判断将值添加到搜索条件中
                //获取页面搜索条件
                var searchData =getUserChooseSearchData();
                //部门id
                if(!isEmpty(searchData.organId)){
                    aoData.organId=searchData.organId;
                }
                //工号
                if(!isEmpty(searchData.loginName)){
                    aoData.loginName=searchData.loginName;
                }
                //姓名
                if(!isEmpty(searchData.realName)){
                    aoData.realName=searchData.realName;
                }
                //aoData = $.extend(aoData, getUserChooseSearchData());
                return aoData;
            },
            "oneSelectCheck":oneSelectCheck,
            "selectCheck":selectCheck,
            "fnInitComplete": function(settings, json) {
                //datatable加载完后重定位弹窗
                dgg.relocation($('.layerIndex').val())
            },
            "fnInfoCallback": function( settings ) {
                dgg.relocation($('.layerIndex').val());
            },
            "aoColumns": [
                {
                    "sClass": "check-th",
                    "orderable": false,
                    "data": "ID",
                    "render": function (data, type, full, meta) {
                        return '<input type="checkbox"  class="checkchild"  value="' + data + '" />';
                    }
                },
                {
                    "title":"工号",
                    "data": "loginName",
                    "orderable": false
                },
                {
                    "title":"姓名",
                    "data": "realName",
                    "orderable": false
                },
                {
                    "title":"部门",
                    "data": "orgName",
                    "orderable": false
                }
            ],
        });
        return tableUser;
    },
    //该方法只针对不使用select2的情况
    clearUser:function (obj) {
        $(obj).parent().find('input').val('');
        $(obj).parent().find('select').empty();
    }
};

// 获取搜索数据
function getUserChooseSearchData() {
    return $("#userChooseForm").serializeObject();
}

